package com.hk.config.parse;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.SingleSelectionModel;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.hk.config.Bean;
import com.hk.config.Property;

public class ConfigManager {
	private static  Map<String,Bean> map;
	//1.读取配置文件
	public static Map<String,Bean> getConfig(String url) {
		//创建一个用于返回的容器
		map = new HashMap<String,Bean>();
		InputStream is = ConfigManager.class.getClassLoader().getResourceAsStream(url);
		SAXReader reader = new SAXReader();
		Document doc = null;
		try {
			 doc = reader.read(is);
		} catch (DocumentException e) {
			e.printStackTrace();
			throw new RuntimeException("请检查xml配置是否正确"); 
		}
		//定义一个xPath路径，取出所有的Bean元素
		String xPath = "//bean";
		List<Element> elements = doc.selectNodes(xPath);
		if(elements!=null) {
			for(Element ele:elements) {
				Bean bean = new Bean();
				String id = ele.attributeValue("id");
				String className = ele.attributeValue("class");
				String scope =  ele.attributeValue("scope");
				bean.setId(id);
				bean.setClassName(className);
				if(scope!=null)
					bean.setScope(scope);
				List<Element> props = ele.elements("property");
				if(props!=null) {
					//List<Property> propList =  new ArrayList<>();
					for(Element prop :props) {
						Property t_prop =  new Property();
						String name = prop.attributeValue("name");
						String value = prop.attributeValue("value");
						String ref = prop.attributeValue("ref");
						t_prop.setName(name);
						t_prop.setValue(value);
						t_prop.setRef(ref);
						bean.getProperties().add(t_prop);
					}
				}
				map.put(id,bean);
			}
		}
		return map;
	}
}
